<style>
    html, body {
        margin: 0!important;
        padding: 0!important;
    }
</style>

<title>Promises and RecordRTC</title>
<h1>Promises and RecordRTC</h1>

<br>
<button id="btn-start-recording">Start Recording</button>
<button id="btn-stop-recording" disabled>Stop Recording</button>

<hr>
<video controls autoplay playsinline></video>

<script src="https://www.webrtc-experiment.com/RecordRTC.js"></script>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
var video = document.querySelector('video');

function captureCamera(callback) {
    navigator.mediaDevices.getUserMedia({audio: true, video: true}).then(function(camera) {
        callback(camera);
    }).catch(function(error) {
        console.error(error);
    });
}

function stopRecordingCallback() {
    video.srcObject = null;
    
    recorder.getBlob().then(function(blob) {
        video.src = URL.createObjectURL(blob);
        recorder.camera.stop();
    });
}

var recorder; // globally accessible

document.getElementById('btn-start-recording').onclick = function() {
    this.disabled = true;
    captureCamera(function(camera) {
        video.srcObject = camera;

        recorder = new RecordRTCPromisesHandler(camera, {
            type: 'video'
        });

        recorder.startRecording().then(function() {
            console.info('startRecording success');
        }).catch(function(error) {
            console.error('startRecording failure', error);
        });

        // var internal = recorder.recordRTC.getInternalRecorder();
        // alert(internal instanceof MediaStreamRecorder);

        // release camera on stopRecording
        recorder.camera = camera;

        document.getElementById('btn-stop-recording').disabled = false;
    });
};

document.getElementById('btn-stop-recording').onclick = function() {
    this.disabled = true;
    recorder.stopRecording().then(function() {
        console.info('stopRecording success');
        stopRecordingCallback();

        // recorder.getDataURL().then(function(dataURL) {}).catch(errorCB);
    }).catch(function(error) {
        console.error('stopRecording failure', error);
    });
};
</script>

<footer style="margin-top: 20px;"><small id="send-message"></small></footer>
<script src="https://www.webrtc-experiment.com/common.js"></script>
